<?php

namespace app\common\logic;

use app\common\helper\NetPay;
use app\common\helper\QrcodeHelper;
use app\common\logic\common\PayLogic;
use app\common\model\Cart;
use app\common\model\Comment;
use app\common\model\Goods;
use app\common\model\GoodsItem;
use app\common\model\Group;
use app\common\model\GroupOrder;
use app\common\model\Order;
use app\common\model\OrderItem;
use app\common\model\Pay;
use app\common\model\User;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Queue;
use think\helper\Str;

class OrderLogic extends BaseLogic
{
    // 生成单号
    public static function getOutTradeNo($length = 10)
    {
        return date('YmdHis') . Str::random($length,1);
    }

    public static function createOrder($data)
    {
        if ($data['from'] == 'cart') {
            $order = self::createCartOrder($data);
        } else {
            $order = self::createBuyOrder($data);
        }
        return $order;
    }
    
    /**
     * @param $order_id
     * @param $user_id
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * author 小李子 2023-10-28 11:46
     * description 取消订单
     */
    public static function cancelOrder($order_id,$user_id)
    {
        $order = Order::where("id",$order_id)
            ->where('user_id',$user_id)
            ->find();
        if (!$order) throwError('订单不存在');
        if ($order->status != -1) throwError('已支付不支持取消');
        $order->delete();
    }
    
    public static function nativePay($order_id)
    {
        $pay_id = PayLogic::createOrUpdatePayOrder($order_id);
        $pay = new NetPay();
        $pay_order = Pay::find($pay_id);
        $order = Order::find($order_id);
        return $pay->createWxNativePay("购买".$order["body"]["goods"]["title"]
            ,$pay_order->out_trade_no,$pay_order->money);
    }

    // 购物车下单
    public static function createCartOrder($data)
    {
        Db::startTrans();
        try {
            validate(\app\validate\Order::class)->scene('cart')->check($data);
            $user = User::where("id",$data['user_id'])->find();
//            if ($user->status !== 1) {
//                throwError('账号待审，暂无法下单');
//            }
            $cart_obj = Cart::where("id","in",$data['cart_ids']);
            $all_money = 0;
            $order_no = self::getOutTradeNo();
            foreach ($cart_obj->select() as $item) {
                $goods = Goods::where("id",$item->goods_id)->find();
                if (!$goods) {
                    throwError('商品不存在');
                }
                $goods_item = GoodsItem::where("id",$item->goods_item_id)->find();
                if (!$goods_item) {
                    throwError('商品不存在');
                }
                if ($goods_item->stock < $item['num']) throwError('库存不足');
                $all_money += $goods_item->price * $item['num'];
                    // 减库存
                $goods_item->stock -= $item['num'];
                $goods_item->sales += $item['num'];
                $goods_item->save();
                $goods->sales += $item['num'];
                if ($goods->is_single == 1) {
                    $goods->stock -= $item['num'];
                }
                $goods->save();

                // 添加子订单
                OrderItem::create([
                    "order_no" => $order_no,
                    "goods_id" => $goods->id,
                    "goods_item_id" => $goods_item->id,
                    "num" => $item['num'],
                    "money" => $goods_item->price,
                    "content" => ['goods'=>$goods,"goods_item"=>$goods_item]
                ]);
            }
            $order = Order::create([
                "user_id" => $data['user_id'],
                "order_no" => $order_no,
                "money" => round($all_money,2),
                "school_id" => $user->school_id,
                "address_id" => $data['address_id'],
                "content" => !empty($data['content']) ? $data['content']: ''
            ]);

            // 创建支付订单
            $pay = Pay::create([
                'user_id' => $data['user_id'],
                'order_no' => $order_no,
                'order_id' => $order->id,
                'type' => 'goods',
                'money' => round($all_money,2),
                'out_trade_no' => $order_no
            ]);


            // 删除购物车
            Cart::destroy($data['cart_ids']);
            Db::commit();
            return ['pay_id'=>$pay->id];
        } catch (ValidateException | Exception $exception) {
            Db::rollback();
            throwError($exception->getMessage());
        }
    }

    // 直接下单
    public static function createBuyOrder($data)
    {
        Db::startTrans();
        try {
            validate(\app\validate\Order::class)->scene('buy')->check($data);
            $order_no = self::getOutTradeNo();
            $buy_goods = $data['goods'];
            $user = User::where("id",$data['user_id'])->find();
//            if ($user->status !== 1) {
//                throwError('账号待审，暂无法下单');
//            }
            $goods = Goods::where("id",$buy_goods[0]['goods_id'])->find();
            $goods_item = GoodsItem::where("id",$buy_goods[0]['item_id'])->find();
            if (!$goods_item || !$goods) {
                throwError('商品不存在');
            }
            $all_money = round($goods_item->price * $buy_goods[0]['num'],2);
            // 添加子订单
            OrderItem::create([
                "order_no" => $order_no,
                "goods_id" => $goods->id,
                "goods_item_id" => $goods_item->id,
                "num" => $buy_goods[0]['num'],
                "money" => $goods_item->price,
                "content" => ['goods' => $goods, "goods_item" => $goods_item]
            ]);
            $order = Order::create([
                "address_id" => $data['address_id'],
                "user_id" => $data['user_id'],
                "order_no" => $order_no,
                "money" => $all_money,
                "school_id" => $user->school_id,
                "content" => !empty($data['content']) ? $data['content']: ''
            ]);

            // 创建支付订单
            $pay = Pay::create([
                'user_id' => $data['user_id'],
                'order_no' => $order_no,
                'order_id' => $order->id,
                'type' => 'goods',
                'money' => round($all_money,2),
                'out_trade_no' => $order_no
            ]);
            Db::commit();
            return ['pay_id'=>$pay->id];
        } catch (ValidateException  | Exception $exception) {
            Db::rollback();
            throwError($exception->getMessage());
        }
    }

    public static function orderPre($data)
    {
        $goodsList = [];
        $can_buy = true;
        $all_money = 0;
        $errmsg = "";
        foreach ($data['goods'] as $item) {
            $goods = Goods::where('id',$item['goods_id'])->find();
            $goods_item = GoodsItem::where("id",$item['item_id'])->find();
            if (!$goods_item || !$goods) {
                $errmsg = '商品不存在';
            } else {
                $all_money += round($goods_item->price * $item['num'],2);
            }
            if ($goods_item->stock < $item['num']) $errmsg = '库存不足';
            $goods_item->num = $item['num'];
            $goodsList[] = [
                "goods" => $goods,
                "item" => $goods_item,
                "errmsg" => $errmsg
            ];
            if ($errmsg) $can_buy = false;
        }
        return [
            "goods" => $goodsList,
            "money" => $all_money,
            "can_buy" => $can_buy,
            "errmsg" => !empty($errmsg) ? $errmsg : ''
        ];
    }

    public static function getOrderList($data)
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] = ['status',"=",$data['status']];
        }
        $where[] = ['user_id',"=",$data['user_id']];
        $list = Order::where($where)
            ->order('id desc')
            ->paginate(["list_rows"=>$data['limit'],"page"=>$data['page'],"query"=>safeInput()]);
        return $list;
    }

    public static function delOrder($data)
    {
        $order = Order::where("id",$data['id'])
            ->with(['item'])
            ->where('user_id',$data['user_id'])->find();
        $order->together(['item'])->delete();
    }

    public static function setOrderStatus($data)
    {
        $order = Order::where("id",$data['id'])
            ->where('user_id',$data['user_id'])
            ->save(['status'=>$data['status']]);
    }

    public static function getOrderDetail($data)
    {
        return Order::where('id',$data['id'])
            ->with(['item','address'])->find();
    }

    public static function createPay($data)
    {
        $pay = Pay::where("id",$data['pay_id'])
            ->where('user_id',$data['user_id'])
            ->find();
        if (!$pay) {
            throwError('订单不存在1');
        }
        
        $out_trade_no = self::getOutTradeNo(15);
        $pay->out_trade_no = $out_trade_no;
        $pay->save();
        $obj = new NetPay();
//      return $obj->createWxPay('订单'.$pay->order_no,$out_trade_no,$pay->money,$data['openid']);
        return $obj->createWxPay('充值'.$out_trade_no,$out_trade_no,$pay->money,$data['openid']);
    }

    public static function orderComment($data)
    {
        $order = Order::where('id',$data['order_id'])->find();
        Db::startTrans();
        try {
            foreach ($data['comment'] as $item=>$value) {
                $c = Comment::where('user_id',$data['user_id'])
                    ->where('goods_id',$value['goods_id'])
                    ->where('item_id',$value['goods_item_id'])
                    ->where('order_id',$data['order_id'])
                    ->find();
                $in = [
                    'user_id' => $data['user_id'],
                    'goods_id' => $value['goods_id'],
                    'item_id' => $value['goods_item_id'],
                    'order_id' => $data['order_id'],
                    'content' => $value['comment']
                ];
                if ($c) {
                    $c->save($in);
                } else {
                    Comment::create($in);
                }
            }
            $order->status = 500;
            $order->save();
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            throwError($exception->getMessage());
        }
    }

    // 退款
    public static function orderReturned($data)
    {
        $order = Order::where('id',$data['id'])->find();
        if ($order->status > 0) { // 没有申请过退款
            $order->status = -1;
            $order->why = $data['why'];
            $order->save();
        } else {
            throwError('您已经申请过退款了');
        }
    }
    
    public static function getBarcode($order_id,$uid)
    {
        if (empty($order_id)) throwError();
        $order = \app\common\model\Order::where("id",$order_id)
            ->where("user_id",$uid)->find();
        if (!$order) throwError();
        throwSuccess([
            "barcode" => (new QrcodeHelper())->barcode($order->order_no)
        ]);
    }
}